/**
 * MagicGame.java
 */
package com.liusoft.android.fmagic;

import java.text.MessageFormat;

import com.liusoft.android.utils.AppUtils;
import com.liusoft.android.utils.LogUtils;

import android.app.*;
import android.view.*;
import android.widget.*;
import android.content.*;
import android.graphics.*;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.util.Linkify;

/**
 * 魔盘游戏入口
 * 向右旋转的规律
 * 
 * 1,1 -> 1,4
 * 1,2 -> 2,4
 * 1,3 -> 3,4
 * 1,4 -> 4,4
 * 
 * 2,1 -> 1,3
 * 2,2 -> 2,3
 * 2,3 -> 3,3
 * 2,4 -> 4,3
 * 
 * @author Winter Lau
 */
public class MagicGame extends Activity implements OnFinishListener {

	private MagicController main_board ;
	private int current_pic;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        this.setTitle(R.string.app_title);
					
        setContentView(R.layout.main);
        //初始化全局变量
        GameGlobal.init(this.getApplicationContext());
        //初始化游戏面板
        main_board = (MagicController)this.findViewById(R.id.main_board);
        this._InitGame(main_board);        
	}

	/**
	 * 游戏初始化
	 * @param board
	 */
	private void _InitGame(MagicController board) {
		MagicSizer sizer = new MagicSizer(_CalcGameRect(),GameGlobal.CELL_ROW,GameGlobal.CELL_COL);
		
        //游戏背景图和前景图
        Bitmap bg = BitmapFactory.decodeResource(getResources(), R.drawable.default_bg);
        Bitmap img = BitmapFactory.decodeResource(getResources(), (current_pic=GameGlobal.get_pic()));

        //读取上次运行状态信息
        String game_state = GameGlobal.read(GameGlobal.PREFS_KEY_CELLS);
        
        board.MC_Init(sizer,bg,img,GameGlobal.is_audio_on(),GameGlobal.is_left_hand(), game_state);
        board.MC_SetOnFinishListener(this);

		if(game_state != null)
			GameGlobal.remove(GameGlobal.PREFS_KEY_CELLS);		
	}

	/**
	 * 计算游戏框的显示大小
	 * @return
	 */
	private Rect _CalcGameRect() {
		int board_left = 0;
		int board_size = 0;
		
		board_size = this.getWindowManager().getDefaultDisplay().getWidth();
		
		return new Rect(board_left,0,board_left+board_size,board_size);
	}
	
	/**
	 * 当游戏完成后
	 */
	@Override
	public void OnFinish(long time) {
		Toast.makeText(this, R.string.done_msg, Toast.LENGTH_SHORT).show();
	}

	/**
	 * 创建菜单
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		this.getMenuInflater().inflate(R.menu.main, menu); 
	    return true;
	}
	
	/**
	 * 当菜单弹出时
	 */
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		LogUtils.debug("Menu", "---> %s", menu.toString());
		return super.onPrepareOptionsMenu(menu);
	}

	/**
	 * 选择菜单项
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onContextItemSelected(item);
		switch(item.getItemId()){
		case R.id.menu_begin:
			if(main_board.MC_IsPause() || main_board.MC_IsRunning()){
				this.showDialog(R.id.menu_begin);
			}
			else
				main_board.MC_Start();
			break;
		case R.id.menu_network:
			break;
		case R.id.menu_setting:
			Intent intent = new Intent(this, MagicSetting.class);
			this.startActivity(intent);
			break;
		case R.id.menu_about:
			this.showDialog(R.id.menu_about);
		}
		return true;
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		if(id == R.id.menu_about) {
			//显示关于对话框
			AppUtils au = new AppUtils(this);
			String fmt_about = getString(R.string.about_game);
			fmt_about = MessageFormat.format(fmt_about, au.getVersionName(), au.getVersionCode());
			TextView tv_about = new TextView(this);
			tv_about.setText(fmt_about);
			tv_about.setTextSize(16);
			tv_about.setPadding(20, 0, 0, 0);
			Linkify.addLinks(tv_about, Linkify.WEB_URLS|Linkify.EMAIL_ADDRESSES);
			
			AlertDialog dlg = new AlertDialog.Builder(this)
				.setTitle(R.string.app_title)
				.setView(tv_about)
				.setPositiveButton(R.string.btn_ok, new DialogInterface.OnClickListener() {					
					@Override
					public void onClick(DialogInterface dialog, int which) {}
				}).create();
			
			return dlg;
		}
		else
		if(id == R.id.menu_begin) {
			//重新开始确认
			return new AlertDialog.Builder(this)
				.setTitle(R.string.app_title)
				.setIcon(android.R.drawable.ic_menu_help)
				.setMessage(R.string.rebegin)
				.setPositiveButton(R.string.btn_yes, new DialogInterface.OnClickListener() {					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						main_board.MC_Start();
					}
				})
				.setNegativeButton(R.string.btn_no, new DialogInterface.OnClickListener() {					
					@Override
					public void onClick(DialogInterface dialog, int which) {}
				})
			.create();			
		}
		
		return super.onCreateDialog(id);
	}

	/**
	 * 按键事件触发
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {		
		if(keyCode == KeyEvent.KEYCODE_DPAD_CENTER && 
				(main_board.MC_IsPause() || main_board.MC_IsRunning()))
		{			
			_ShowPreviewDialog();			
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	/**
	 * 显示预览图和计时器
	 */
	private void _ShowPreviewDialog() {
		LayoutInflater li = this.getLayoutInflater();
		View v = li.inflate(R.layout.preview, null);
		ImageView iv = (ImageView)v.findViewById(R.id.img_preview);
		Bitmap bmp = BitmapFactory.decodeResource(getResources(), this.current_pic);
		Matrix matrix = new Matrix();
		matrix.setRotate(GameGlobal.is_left_hand()?-90:90);
		iv.setImageDrawable(new BitmapDrawable(Bitmap.createBitmap(bmp,0,0,bmp.getWidth(),bmp.getHeight(),matrix,true)));
		
		final AlertDialog dlg = new AlertDialog.Builder(this).setView(v).create();
		iv.setOnTouchListener(new View.OnTouchListener(){
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				dlg.dismiss();
				return false;
			}});
		dlg.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dlg.show();
	}

	@Override
	protected void onStop() {
		//保存游戏状态
	    String game_state = main_board.MC_GetGameArray();
	    if(game_state != null)
	    	GameGlobal.write(GameGlobal.PREFS_KEY_CELLS, game_state);	 
	    
		super.onStop();	
	}

	@Override
	protected void onResume() {
		super.onResume();
		//从设置中更新
		int new_pic = GameGlobal.get_pic();
		if(new_pic != this.current_pic) {
			//更换图片 
			this.current_pic = new_pic;
			main_board.MC_SetForeground(BitmapFactory.decodeResource(getResources(), current_pic));
		}
		main_board.MC_SetAudioOn(GameGlobal.is_audio_on());	
		main_board.MC_SetLeftHand(GameGlobal.is_left_hand());
	}

}
